<template>
    <el-input
      :modelValue="modelValue"
      @update:modelValue="(val) => $emit('update:modelValue', val)"
      v-bind="$attrs"
      @input="handleInput"
      @change="handleChange"
      @blur="handleBlur"
      @focus="handleFocus"
    >
      <template v-if="$slots['prefix']" #prefix>
        <slot name="prefix"></slot>
      </template>
      <template v-if="$slots['suffix']" #suffix>
        <slot name="suffix"></slot>
      </template>
      <template v-if="$slots['prepend']" #prepend>
        <slot name="prepend"></slot>
      </template>
      <template v-if="$slots['append']" #append>
        <slot name="append"></slot>
      </template>
    </el-input>
  </template>
  
  <script lang="ts" setup>
  import { onBeforeUnmount } from 'vue';
  
  /**
   * FormInput 组件 props 定义
   */
  const props = defineProps<{
    modelValue: string;
    debounce?: number; // 防抖延迟时间(ms)
  }>();
  
  /**
   * FormInput 组件 emit 定义
   */
  const emit = defineEmits<{
    (e: 'update:modelValue', value: string): void;
    (e: 'input', value: string): void;
    (e: 'change', value: string): void;
    (e: 'blur', event: FocusEvent): void;
    (e: 'focus', event: FocusEvent): void;
  }>();
  
  // 防抖定时器
  let debounceTimer: ReturnType<typeof setTimeout> | null = null;
  
  // 处理输入事件
  const handleInput = (value: string) => {
    if (props.debounce && props.debounce > 0) {
      if (debounceTimer) {
        clearTimeout(debounceTimer);
      }
      
      debounceTimer = setTimeout(() => {
        emit('input', value);
      }, props.debounce);
    } else {
      emit('input', value);
    }
  };
  
  // 处理变更事件
  const handleChange = (value: string) => {
    emit('change', value);
  };
  
  // 处理失去焦点事件
  const handleBlur = (event: FocusEvent) => {
    emit('blur', event);
  };
  
  // 处理获取焦点事件
  const handleFocus = (event: FocusEvent) => {
    emit('focus', event);
  };
  
  // 组件卸载时清除定时器
  const clearDebounceTimer = () => {
    if (debounceTimer) {
      clearTimeout(debounceTimer);
      debounceTimer = null;
    }
  };
  
  // 在组件卸载前清除定时器
  onBeforeUnmount(() => {
    clearDebounceTimer();
  });
  </script>